package com.it.system.user.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.it.system.user.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Value("${alioss.access-key-id}")
    private String accessKeyId;
    
    @Value("${alioss.access-key-secret}")
    private String accessKeySecret;
    
    @Value("${alioss.endpoint}")
    private String endpoint;
    
    @Value("${alioss.bucket-name}")
    private String bucketName;
    
    @Override
    public String uploadFile(MultipartFile file, String dir) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        
        String originalFilename = file.getOriginalFilename();
        // 确保文件名不为空
        if (originalFilename == null) {
            throw new RuntimeException("文件名不能为空");
        }
        
        // 获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成新的文件名，避免重复
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        // 完整的文件路径
        String objectName = dir + "/" + fileName;
        
        try (InputStream inputStream = file.getInputStream()) {
            // 创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            // 设置ContentLength
            metadata.setContentLength(file.getSize());
            // 设置ContentType
            metadata.setContentType(getContentType(suffix));
            
            // 上传文件
            ossClient.putObject(bucketName, objectName, inputStream, metadata);
            
            // 返回文件访问路径
            return "https://" + bucketName + "." + endpoint + "/" + objectName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
    
    /**
     * 获取文件类型
     */
    private String getContentType(String suffix) {
        if (suffix.equalsIgnoreCase(".jpg") || suffix.equalsIgnoreCase(".jpeg")) {
            return "image/jpeg";
        } else if (suffix.equalsIgnoreCase(".png")) {
            return "image/png";
        } else if (suffix.equalsIgnoreCase(".gif")) {
            return "image/gif";
        } else {
            return "application/octet-stream";
        }
    }
} 